//
//  CZRefreshView.swift
//  微博08
//
//  Created by apple on 16/3/4.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZRefreshView: UIView {

    @IBOutlet weak var tipIcon: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var loadingView: UIImageView!
    
    /// 从xib加载view
    class func refreshView() -> CZRefreshView {
        return NSBundle.mainBundle().loadNibNamed("CZRefreshView", owner: nil, options: nil).last as! CZRefreshView
    }

    /**
     箭头旋转
     
     - parameter isUp: 旋转方向
     */
    func rotationTipIcon(isUp: Bool) {
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipIcon.transform = isUp ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
        }
    }
    
    /**
     开始旋转
     */
    func startLoading() {
        // 避免动画重复
        
        let animKey = "rotationAnim"
        
        // 判断动画是否已经添加过了
        if let _ = loadingView.layer.animationForKey(animKey) {
            // 能进来说明已经添加了动画
            print("已经添加了动画")
            return
        }
        
        // 隐藏上面的tipView
        tipView.hidden = true
        
        // loadingView旋转
        let rotationAnim = CABasicAnimation(keyPath: "transform.rotation")
        rotationAnim.toValue = M_PI * 2
        rotationAnim.repeatCount = MAXFLOAT
        rotationAnim.duration = 0.25
        rotationAnim.removedOnCompletion = false
        
        // 添加动画
        loadingView.layer.addAnimation(rotationAnim, forKey: animKey)
    }
    
    /// 停止旋转,显示箭头
    func stopLoading() {
        loadingView.layer.removeAllAnimations()
        
        // 显示上面的tipView
        tipView.hidden = false
    }
}
